import io from '@hyoga/uni-socket.io';
import config from '@/common/environment.js';
import store from '@/store'
import * as localMessage from '@/util/local-message.js'
import noticeVoice from '@/util/notice-voice.js'

const WEBSOCKET_SERVICE = config.WEBSOCKET_SERVICE + '/group';
let socket = null
let init = false
let timer
export default {
  getReady () {
    return init
  },
  initWebScoket (vm) {
    init = true
    socket = io(WEBSOCKET_SERVICE, {
      reconnectionDelayMax: 4000,
      query: {t: store.state.vuex_token },
      transports: [ 'websocket', 'polling' ],
      timeout: 12000,
    });
    socket.on('connect', () => {
      vm.$u.networkSuccess(true)
      console.log('socket连接成功');
    });

    socket.on('joinSuccess', () => {
      console.log('加入成功');
      clearInterval(timer)
    });

    socket.on('disconnect', () => {
      console.log('socket断开连接');
      vm.$u.networkSuccess(false)
    });
    socket.on('rollbackMessage', (params) => {
      console.log('撤回消息', params);
      vm.$u.refreshChatGroupList()
      localMessage.rollbackMessage(params)
      uni.$emit('rollbackMessage', params)
    });

    socket.on('receiveMessage', params => {
      uni.$emit('receiveMessage', params)
    })

    socket.on('drop_relations', params => {
      uni.$emit('drop_relations', params)
    })

    socket.on('refresh', s => {
      vm.$u.debounce(() => {
        if (s.send_user_id !== vm.vuex_userInfo.id) noticeVoice.playReceive()
        vm.$u.refreshChatGroupList()
      }, 200)
    })

    socket.on('refreshGroup', (s) => {
      if (s.group_id) uni.$emit('refreshChattingInfo_' + s.group_id)
    })

    socket.on('refreshFriendApply', () => {
      uni.$emit('refreshFriendApply')
    })

    socket.on('refreshContact', () => {
      vm.$u.refreshContactList()
    })
    return socket
  },
  emit(event, data) {
    socket.emit(event, data)
  },
  joinGroup ({
    _this,
    groupId
  }) {
    if (!init) {
      this.initWebScoket(_this)
    }
    clearInterval(timer)
    timer = setInterval(() => {
      socket.emit('join', groupId)
    }, 1200)
    
  },
  leaveGroup ({
    groupId
  }) {
    socket.emit('leave', groupId)
  },
  disconnect () {
    socket.disconnect()
  }
}